package com.ChatServer.ferradm.cs.newpaltz.edu;
import dcf.*;
import com.ChatServer.ferradm.cs.newpaltz.edu.*;
import common.JoinRequest;
import common.TextMessage;

public class ChatServerBehavior extends Behavior {

	private IService messageClientService;
	
	public ChatServerBehavior(Endpoint lsEndpoint, Endpoint localEndpoint) throws InitializationException {
		
		super(lsEndpoint,localEndpoint);
		messageClientService = createService("MsgClient", IService.ServiceType.PUBLISHER);
		
	}
	
    public void interpretMessage(Message message) {

    	if (message instanceof BindNotificationMessage) {
    		
			System.out.println(getClass().getName() + ".interpretMessage():");
			System.out.println("   Recieved bind notification for service "
					+ ((BindNotificationMessage) message).getServiceName());
			

		} else if (message instanceof TextMessage) {

			System.out.println(getClass().getName() + ".interpretMessage():");
			System.out.println("   Recieved text message.");
			

			messageClientService.send(message);

		} else if (message instanceof JoinRequest) {

			// Send a text message to the clients indicating a user has left.
			//
			
			System.out.println(getClass().getName() + ".interpretMessage():");
			System.out.println("   Recieved JoinRequest from "
					+ message.getSenderEndpoint().getHost() + ":"
					+ message.getSenderEndpoint().getPort());
			

			TextMessage tm = new TextMessage("**", ((JoinRequest) message)
					.getId()
					+ " has entered the chat. **");

			messageClientService.send(tm);

		} else if (message instanceof UnboundNotificationMessage) {

			// Send a text message to the clients indicating a user has left.
			//
			System.out.println(getClass().getName() + ".interpretMessage():");
			System.out.println("   Recieved UnboundNotificationMessage from " +
					           message.getSenderEndpoint().getHost() + ":" +
					           message.getSenderEndpoint().getPort() + " for service " +
					           ((UnboundNotificationMessage)message).getServiceName());

		} else {

			System.out.println(getClass().getName() + ".interpretMessage():");
			System.out.println("   Recieved unexpected message: " + message.getClass().getName());

		}
		   
	}
}
